package org.chen.ctrip.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.ctrip.entity.ContentReplaceRule;
import org.chen.ctrip.mapper.ContentReplaceRuleMapper;
import org.chen.ctrip.service.ContentReplaceRuleService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;

// ContentReplaceRuleServiceImpl.java
@Slf4j
@Service
public class ContentReplaceRuleServiceImpl extends ServiceImpl<ContentReplaceRuleMapper, ContentReplaceRule> implements ContentReplaceRuleService {

    @Override
    public List<ContentReplaceRule> getEnabledRules() {
        QueryWrapper<ContentReplaceRule> wrapper = new QueryWrapper<>();
        wrapper.eq("enabled", true);
        wrapper.orderByAsc("sort_order", "id");
        return list(wrapper);
    }

    @Override
    public String applyReplaceRules(String content) {
        if (content == null || content.isEmpty()) {
            return content;
        }

        List<ContentReplaceRule> rules = getEnabledRules();
        if (rules.isEmpty()) {
            return content;
        }

        String result = content;

        for (ContentReplaceRule rule : rules) {
            try {
                result = applyRule(result, rule);
            } catch (Exception e) {
                log.error("应用替换规则失败，规则ID: {}, 规则名称: {}, 错误: {}",
                        rule.getId(), rule.getRuleName(), e.getMessage());
                throw new RuntimeException(String.format("应用替换规则失败，规则ID: %s, 规则名称: %s, 错误: %s",
                        rule.getId(), rule.getRuleName(), e.getMessage()));
            }
        }

        return result;
    }

    private String applyRule(String content, ContentReplaceRule rule) {
        String sourceText = rule.getSourceText();
        String targetText = rule.getTargetText() != null ? rule.getTargetText() : "";

        return switch (rule.getRuleType()) {
            case 1 -> // 精确匹配
                    content.replace(sourceText, targetText);
            case 2 -> // 正则表达式
                    content.replaceAll(sourceText, targetText);
            case 3 -> // 包含匹配（忽略大小写）
                    content.replaceAll("(?i)" + Pattern.quote(sourceText), targetText);
            default -> {
                log.warn("未知的规则类型: {}", rule.getRuleType());
                yield content;
            }
        };
    }

    @Override
    public void saveRule(ContentReplaceRule rule) {
        rule.setCreateTime(LocalDateTime.now());
        rule.setUpdateTime(LocalDateTime.now());
        if (rule.getEnabled() == null) {
            rule.setEnabled(true);
        }
        if (rule.getSortOrder() == null) {
            rule.setSortOrder(0);
        }
        save(rule);
    }

    @Override
    public void updateRule(ContentReplaceRule rule) {
        rule.setUpdateTime(LocalDateTime.now());
        updateById(rule);
    }

    @Override
    public void deleteRule(Long id) {
        removeById(id);
    }

    @Override
    public void toggleRuleStatus(Long id, Boolean enabled) {
        ContentReplaceRule rule = getById(id);
        if (rule != null) {
            rule.setEnabled(enabled);
            rule.setUpdateTime(LocalDateTime.now());
            updateById(rule);
        }
    }
}